package com.hd.tiyu.yuejian.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.hd.tiyu.yuejian.Adapter.DashiketangAdapter;
import com.hd.tiyu.yuejian.JavaBean.Dashi;
import com.hd.tiyu.yuejian.JavaBean.Register;
import com.hd.tiyu.yuejian.JavaBean.ShaituDetail;
import com.hd.tiyu.yuejian.LoginActivity;
import com.hd.tiyu.yuejian.Model.ListsModel;
import com.hd.tiyu.yuejian.Model.PhotoModel;
import com.hd.tiyu.yuejian.Model.UserModel;
import com.hd.tiyu.yuejian.R;
import com.squareup.picasso.Picasso;

import java.io.File;
import java.io.IOException;
import java.util.List;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static android.R.attr.data;


/**
 * Created by admin on 2017/10/24.
 */

public class AddShaituActivity extends AppCompatActivity {
    private String FilePath;
    private EditText text_add;
    private TextView Fabu;
    private ImageView  sf_addphoto;
    private ImageView iv_image;
    private static final int PHOTO_REQUEST_CAREMA = 1;// 拍照
    private static final int PHOTO_REQUEST_GALLERY = 2;// 从相册中选择
    private static final int PHOTO_REQUEST_CUT = 3;// 结果


    private static final String PHOTO_FILE_NAME = "temp_photo.jpg";
    private File tempFile;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_addshaitu);
        initViews();
        initEvents();
    }

    public void upload(){
//        File file = new File(FilePath);
//        RequestBody imageBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
//        MultipartBody.Part body = MultipartBody.Part.createFormData("thumb0", file.getName(), imageBody);
        String title = String.valueOf(text_add.getText());
        SharedPreferences mSharedPreferences = getSharedPreferences("loginUser", Context.MODE_PRIVATE);
        String userid = mSharedPreferences.getString("user_id", "");
        PhotoModel model=new PhotoModel();
        Call<ResponseBody> call = model.addpost(userid,title,null);
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                    try {
                        byte[] data = response.body().bytes();
                        String text = new String(data);
                        int uid = Integer.parseInt(text);
                        if (uid > 0) {
                            Toast.makeText(AddShaituActivity.this, "晒图发布成功！！！", Toast.LENGTH_SHORT).show();
                            finish();
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {

            }
        });



    }

    private void initViews() {
        text_add = (EditText) findViewById(R.id.text_add);
        sf_addphoto = (ImageView) findViewById(R.id.sf_addphoto);
        Fabu=(TextView)findViewById(R.id.add_shaitu);
        iv_image=(ImageView)findViewById(R.id.iv_image);
    }
    private void initEvents() {
        sf_addphoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent=new Intent(Intent.ACTION_PICK);
                intent.setType("image/*");
                startActivityForResult(intent,PHOTO_REQUEST_GALLERY);
            }
        });

        Fabu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                upload();
            }
        });

    }
    private void getData() {
        String title = String.valueOf(text_add.getText());
        SharedPreferences mSharedPreferences = getSharedPreferences("loginUser", Context.MODE_PRIVATE);
        String userid = mSharedPreferences.getString("user_id", "");
        PhotoModel model = new PhotoModel();
        Call<ResponseBody> call = model.addpost(userid,title,null);
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                ResponseBody body=response.body();
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {

            }
        });
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(requestCode==PHOTO_REQUEST_GALLERY){
            if(data!=null){
                Uri uri=data.getData();
                Bitmap bm=data.getParcelableExtra("data");
                //使用系统的一个工具类，参数列表为 Bitmap Width,Height  这里使用压缩后显示，否则在华为手机上ImageView 没有显示
                //iv_image.setImageBitmap(ThumbnailUtils.extractThumbnail(bm, 100, 100));

                this.iv_image.setImageBitmap(bm);

                String[] proj = { MediaStore.Images.Media.DATA };
                // 好像是android多媒体数据库的封装接口，具体的看Android文档
                Cursor cursor = managedQuery(uri, proj, null, null, null);
                // 按我个人理解 这个是获得用户选择的图片的索引值
                int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                // 将光标移至开头 ，这个很重要，不小心很容易引起越界
                cursor.moveToFirst();
                // 最后根据索引值获取图片路径
                FilePath= cursor.getString(column_index);
                //text_add.setText(FilePath);
                //裁剪图片
                //crop(uri);
            }
        }
//        else if(requestCode==PHOTO_REQUEST_CUT){
//            if(null!=data){
//                Bitmap bitmap=data.getParcelableExtra("data");
//                this.iv_image.setImageBitmap(bitmap);
//            }
//        }
        super.onActivityResult(requestCode, resultCode, data);
    }


    private void crop(Uri uri){
        // 裁剪图片意图
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        // 裁剪框的比例，1：1
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // 裁剪后输出图片的尺寸大小
        intent.putExtra("outputX", 250);
        intent.putExtra("outputY", 250);
        intent.putExtra("outputFormat", "JPEG");// 图片格式
        intent.putExtra("noFaceDetection", true);// 取消人脸识别
        intent.putExtra("return-data", true);
        // 开启一个带有返回值的Activity，请求码为PHOTO_REQUEST_CUT
        startActivityForResult(intent, PHOTO_REQUEST_CUT);
    }

    private boolean hasSdcard(){
        if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
            return true;
        }else {
            return false;
        }
    }
}
